題目:
We are playing the Guess Game. The game is as follows:
I pick a number from 1 to n. You have to guess which number I picked.
Every time you guess wrong, I will tell you whether the number I picked is higher or lower than your guess.
You call a pre-defined API int guess(int num), which returns three possible results:
-1: Your guess is higher than the number I picked (i.e. num > pick).
1: Your guess is lower than the number I picked (i.e. num < pick).
0: your guess is equal to the number I picked (i.e. num == pick).
Return the number that I picked.
給定一數n,題目會在1~n的範圍選一個目標數(target)
題目有提供函數guess(x)來判斷target和x的關係
若x>target,回傳-1
x< target,回傳1
x==target,回傳0
透過該函數推測並回傳target
這題基本上就是在和題目玩終極密碼(一個充斥二分搜要素的兒時遊戲)
# The guess API is already defined for you.
# @param num, your guess
# @return -1 if num is higher than the picked number
# 1 if num is lower than the picked number
# otherwise return 0
# def guess(num: int) -> int:
class Solution:
def guessNumber(self, n: int) -> int:
l=1
r=n
while l<=r:
mid=(l+r)//2
if guess(mid)==1:
l=mid+1
elif guess(mid)==-1:
r=mid-1
else:
return mid
在1~n的範圍進行二分搜
設下限l=1跟上限r=n,mid定義為(1+r)//2
若guess(mid)等於1(mid< target),l提高到mid+1
若guess(mid)等於-1(mid>target),r降低到mid-1
一旦guess(mid)等於0就回傳mid(猜中了)
最後執行時間31ms(faster than 91.30%)
那我們下題見